package com.chixing.controller;


import com.chixing.pojo.Cart;
import com.chixing.pojo.Customer;
import com.chixing.service.ShoppingCartService;
import com.chixing.util.ServerResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;

@Controller
public class ShoppingCartController {
  @Autowired
  private ShoppingCartService shoppingCartService;


  @GetMapping("/shopCart")
  public ModelAndView getByCusId(HttpSession session) {
    Customer loginCustomer = (Customer) session.getAttribute("loginCustomer");
    ServerResult all = shoppingCartService.getByCusId(loginCustomer.getCustumerId());
    ModelAndView mav = new ModelAndView();
    if (all.getCode() == 200) {
      mav.addObject("shopCarts" , all.getData());
    }
    mav.setViewName("shoppingCart/shopCart");

    return mav;

  }

  @PostMapping("/shopCart/save")
  @ResponseBody
  public ServerResult save(Cart cart ,HttpSession session) {
    Customer loginCustomer = (Customer)session.getAttribute("loginCustomer");
    cart.setCustomerId(loginCustomer.getCustumerId());
    return shoppingCartService.saveCart(cart);
  }

  @PostMapping("shopCart/deleteCart/{cartId}")
  public String delete(@PathVariable("cartId") Integer cartId) {

    shoppingCartService.deleteCart(cartId);

    return "redirect:/shopCart";
  }
}
